package handlers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"werewolf/core"
)

func AiHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	types := r.URL.Query().Get("type")
	typeId, err := strconv.Atoi(types)
	if err != nil {
		http.Error(w, "Invalid type", http.StatusBadRequest)
		return
	}
	//type为1，检测当前对局是否存在ai玩家
	if typeId == 1 {
		room := r.URL.Query().Get("room")
		handle, err := core.Connection()
		if err != nil {
			http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		defer handle.Close()

		var exists bool
		err = handle.QueryRow("SELECT EXISTS(SELECT 1 FROM Ai_info WHERE RmNo = ?)", room).Scan(&exists)
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}

		if exists {
			fmt.Fprint(w, "1") //当前对局存在ai玩家
		} else {
			fmt.Fprint(w, "0") //当前对局存在ai玩家
		}
	} else if typeId == 2 {
		//type为2，在轮询中检测当前行动回合是否轮到局内ai玩家行动
		room := r.URL.Query().Get("room")
		airole := r.URL.Query().Get("role")
		handle, err := core.Connection()
		if err != nil {
			http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		defer handle.Close()
		role := ""
		roleint := 0

		var exists bool
		err = handle.QueryRow("SELECT EXISTS(SELECT 1 FROM ai_info WHERE RmNo = ?)", room).Scan(&exists)
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		if exists {
			survival := 0
			err = handle.QueryRow("SELECT Survival FROM player WHERE No =1 AND RmNo = ?", room).Scan(&survival) //判断ai是否还存活
			if err != nil {
				http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			}
			if survival == 1 {
				err = handle.QueryRow("SELECT Role,RoleInt FROM ai_info WHERE RmNo = ?", room).Scan(&role, &roleint)
				if err != nil {
					http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
					return
				}
				if role == airole {
					fmt.Fprint(w, roleint) //当前角色是ai,返回ai的角色编号
				} else {
					fmt.Fprint(w, "0") //当前角色不是ai
				}
			}

		} else {
			fmt.Fprint(w, "0") //当前角色不是ai
		}

	} else if typeId == 3 {
		room := r.URL.Query().Get("room")
		handle, err := core.Connection()
		if err != nil {
			http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		defer handle.Close()

		var exists bool
		err = handle.QueryRow("SELECT EXISTS(SELECT 1 FROM ai_info WHERE RmNo = ?)", room).Scan(&exists)
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}

		if exists {
			//当前对局存在ai玩家，进行下一步判断，判断ai是否已经死亡
			survival := 0
			err = handle.QueryRow("SELECT Survival FROM player WHERE No =1 AND RmNo = ?", room).Scan(&survival)
			if err != nil {
				http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			}
			if survival == 1 {
				fmt.Fprint(w, "1")
			} else {
				fmt.Fprint(w, "0") //已经死亡，无需下一步行动（与不存在的处理相同）
			}
			//根据查询到的ai死亡状态返回响应信息
		} else {
			fmt.Fprint(w, "0") //不存在
		}
		//判断当局是否有ai玩家并判断当前ai玩家是否已经死亡
	} else if typeId == 4 {
		room := r.URL.Query().Get("room")
		handle, err := core.Connection()
		if err != nil {
			http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		defer handle.Close()

		var exists bool
		err = handle.QueryRow("SELECT EXISTS(SELECT 1 FROM ai_info WHERE RmNo = ?)", room).Scan(&exists)
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}

		if exists {
			//当前对局存在ai玩家，进行下一步判断，提取发送的编号，判断本次死亡的玩家是否是ai
			id := r.URL.Query().Get("id")
			idint, err := strconv.Atoi(id)
			if err != nil {
				http.Error(w, "Invalid id", http.StatusBadRequest)
				return
			}
			aiid := 0
			airole := ""
			err = handle.QueryRow("SELECT AiId,Role FROM ai_info WHERE RmNo = ?", room).Scan(&aiid, &airole)
			if err != nil {
				http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			}
			if aiid == idint {
				if airole == "w-king" {
					fmt.Fprint(w, "2") //返回2代表当前发表遗言的是ai狼王
				} else if airole == "g-hunter" {
					fmt.Fprint(w, "3") //返回3代表当前发表遗言的是ai猎人
				} else {
					fmt.Fprint(w, "1") //返回1代表当前发表遗言的是ai但是不是狼王或猎人
				}
			} else {
				fmt.Fprint(w, "0") //当前发表遗言的玩家不是ai
			}
			//根据查询到的ai死亡状态返回响应信息
		} else {
			fmt.Fprint(w, "0") //不存在
		}
		//type为4，当前发表遗言的是否为ai玩家
	} else if typeId == 5 {
		//type为5，当ai是狼人时，查询当前房间是否有其他狼人角色存活
		room := r.URL.Query().Get("room")
		handle, err := core.Connection()
		if err != nil {
			http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		defer handle.Close()
		role := ""
		roleint := 0

		var exists bool
		err = handle.QueryRow("SELECT EXISTS(SELECT 1 FROM ai_info WHERE RmNo = ?)", room).Scan(&exists)
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		if exists {
			err = handle.QueryRow("SELECT Role,RoleInt FROM ai_info WHERE RmNo = ?", room).Scan(&role, &roleint)
			if err != nil {
				http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
				return
			}
			if role == "w" { //ai是狼人且当前只剩ai一个狼人玩家（不包含其他特殊狼），且ai狼人还存活
				//当前对局存在ai玩家，进行下一步判断，判断ai是否已经死亡
				survival := 0
				err = handle.QueryRow("SELECT Survival FROM player WHERE No =1 AND RmNo = ?", room).Scan(&survival)
				if err != nil {
					http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
				}
				if survival == 1 {
					flag := 1
					addRole := ""
					wn0 := 0
					fn0 := 0
					err = handle.QueryRow("SELECT Role,Werewolf,Folk FROM game WHERE RmNo =?", room).Scan(&addRole, &wn0, &fn0)
					if err != nil {
						http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
						return
					}
					var roles []string
					if addRole != "" {
						roles = strings.Split(addRole, ";")
					}
					//此处加入了所有特殊角色
					for i := 0; i < wn0; i++ {
						roles = append(roles, "w")
					}
					for i := 0; i < fn0; i++ {
						roles = append(roles, "f")
					} //加入普通狼和平民
					rows, err := handle.Query("SELECT Role,Survival,No FROM player WHERE RmNo = ? AND No!=1", room)
					if err != nil {
						http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
						return
					}
					for rows.Next() {
						var role int
						var survival int
						if err := rows.Scan(&role); err != nil {
							http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
							return
						}
						if err = rows.Scan(&survival); err != nil {
							http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
							return
						}
						if (roles[role-1] == "w") && survival == 1 {
							flag = 0
							break
						}
					}
					if flag == 1 {
						fmt.Fprint(w, "1") //当前房间不存在其他狼人角色存活
					} else {
						fmt.Fprint(w, "0") //当前房间存在其他狼人角色存活
					}
				} else {
					fmt.Fprint(w, "0") //已经死亡，无需下一步行动（与不存在的处理相同）
				}

			} else {
				fmt.Fprint(w, "0") //ai不是狼人，无需下一步行动}
			}
		} else {
			fmt.Fprint(w, "0") //本局没有ai
		}
	} else if typeId == 6 {
		//type为6，判断当前ai是否为骑士，且是否存活
		room := r.URL.Query().Get("room")
		handle, err := core.Connection()
		if err != nil {
			http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		defer handle.Close()
		role := ""
		roleint := 0
		var exists bool
		err = handle.QueryRow("SELECT EXISTS(SELECT 1 FROM ai_info WHERE RmNo = ?)", room).Scan(&exists)
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		if exists {
			err = handle.QueryRow("SELECT Role,RoleInt FROM ai_info WHERE RmNo = ?", room).Scan(&role, &roleint)
			if err != nil {
				http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
				return
			}
			if role == "g-knight" { //ai是狼人且当前只剩ai一个狼人玩家（不包含其他特殊狼）
				survival := 0
				err = handle.QueryRow("SELECT Survival FROM player WHERE No =1 AND RmNo = ?", room).Scan(&survival)
				if err != nil {
					http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
				}
				if survival == 1 {
					fmt.Fprint(w, "1") //是骑士且仍存活
				} else {
					fmt.Fprint(w, "0") //是骑士，但是已经死亡
				}
			}
		} else {
			fmt.Fprint(w, "0") //本局没有ai
		}
	}
}

//检测当局是否存在ai玩家，ai玩家是否为狼人阵营的角色，并且当局是否有狼人阵营的玩家

//判断当前行动的角色是否为ai

func AiWolvesteammateHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	handle, err := core.Connection()
	if err != nil {
		http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
	}
	roomno := r.URL.Query().Get("room")
	defer handle.Close()
	airole := ""
	err = handle.QueryRow("SELECT Role FROM ai_info WHERE RmNo = ?", roomno).Scan(&airole)
	if err != nil {
		http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
		return
	} //查询ai的角色
	if airole == "w" || airole == "w-king" || airole == "w-devil" || airole == "w-knight" { //如果ai是狼，则告知狼队友,新增狼人角色
		var wn0, fn0, setroles = 0, 0, ""
		err = handle.QueryRow("SELECT Role,Werewolf,Folk FROM game WHERE RmNo =?", roomno).Scan(&setroles, &wn0, &fn0)
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		var roles []string
		if setroles != "" {
			roles = strings.Split(setroles, ";")
		}

		for i := 0; i < wn0; i++ {
			roles = append(roles, "w")
		}
		for i := 0; i < fn0; i++ {
			roles = append(roles, "f")
		} //加入普通狼和平民

		var wolves []int
		rows, err := handle.Query("SELECT Role,No FROM player WHERE RmNo =?", roomno)
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		for rows.Next() {
			var no int
			var role int
			if err := rows.Scan(&role, &no); err != nil {
				http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
				return
			}

			if roles[role-1] == "w" || roles[role-1] == "w-king" || roles[role-1] == "w-devil" || roles[role-1] == "w-knight" {
				wolves = append(wolves, no)
			}
		}
		roomInt, err := strconv.Atoi(roomno)
		if err != nil {
			http.Error(w, "Failed to converse:"+err.Error(), http.StatusInternalServerError)
			return
		}
		ts := wolfTeammateInformed(roomInt, wolves)
		if ts {
			fmt.Fprint(w, "1") //回复1代表ai正确接收
		} else {
			fmt.Fprint(w, "0") //回复0代表没有正确接收
		}
	}
}

func AiwolveskillHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to converse:"+err.Error(), http.StatusInternalServerError)
		return
	}

	//调用函数得出ai狼人可以击杀的对象列表
	namelist := NameList(1, roomInt)
	bekilled := werewolvesKill(roomInt, 1, namelist) //返回要杀的人，第二个参数
	if bekilled == -1 {
		//出现错误进行处理
	} else {
		fmt.Fprint(w, bekilled) //将整数写入数据回复选择击杀的对象

	}
} //与ai进行交谈，选择击杀对象

func Aiwitchpoison(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	RoomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	namelist := NameList(2, RoomInt) //调用函数得出女巫可以毒杀的对象列表
	id := witchPoison(RoomInt, namelist)
	//改写提供可以毒杀的对象列表

	if id == 0 {
		fmt.Fprint(w, 0) //将整数写入数据的回复部分
		//返回不使用毒药
	} else if id > 0 {
		fmt.Fprint(w, id)
		//返回要毒杀的玩家
	} else if id == -1 {
		fmt.Println("error to call witchPoison")
	} //调用的函数出错

} //询问ai是否使用毒药并返回使用毒药的对象（前端判断ai是否有毒药后选择调用）

func Aiantidote(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	bekilled := r.URL.Query().Get("bekilled") //获取昨晚狼人选择击杀的信息
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	bekilledInt, err := strconv.Atoi(bekilled)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	id := witchAntidote(roomInt, bekilledInt) //调用witchAntidote函数，返回是否使用解药
	if id == -1 {
		//出现错误进行处理
	} else {
		fmt.Fprint(w, id) //将整数写入数据的回复部分，1代表使用，0代表不使用
	}

} //告知ai昨晚狼人选择击杀的对象，询问ai是否使用解药，返回ai的决定（前端判断ai是否）

func Aiseercheck(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}

	checktype := r.URL.Query().Get("type")
	if checktype == "1" {
		namelist := NameList(3, roomInt)
		checkid := seerVerification(roomInt, namelist) //询问ai想要查询的对象并返回查询对象
		if checkid != -1 {
			fmt.Fprint(w, checkid) //将ai预言家想要查验的玩家编号写入回复
		}
		//返回ai预言家想要查验的对象
	} else if checktype == "2" {
		//告知预言家查验结果
		identity := r.URL.Query().Get("identity")
		checkid := r.URL.Query().Get("checkid")
		checkidInt, err := strconv.Atoi(checkid)
		if err != nil {
			http.Error(w, "Failed to convert:"+err.Error(), http.StatusInternalServerError)
			return
		}
		result := seerVerificationInformed(roomInt, checkidInt, identity)
		if !result {
			//告知出错
			http.Error(w, "Failed to inform", http.StatusInternalServerError)
			return
		}
	}
}

func Aidevilcheck(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}

	checktype := r.URL.Query().Get("type")
	if checktype == "1" {
		namelist := NameList(8, roomInt)
		checkid := devilVerification(roomInt, namelist) //询问ai想要查询的对象并返回查询对象
		if checkid != -1 {
			fmt.Fprint(w, checkid) //将ai恶魔想要查验的玩家编号写入回复
		}
		//返回ai恶魔想要查验的对象
	} else if checktype == "2" {
		//告知ai恶魔查验结果
		identity := r.URL.Query().Get("identity")
		checkid := r.URL.Query().Get("checkid")
		checkidInt, err := strconv.Atoi(checkid)
		if err != nil {
			http.Error(w, "Failed to convert:"+err.Error(), http.StatusInternalServerError)
			return
		}
		result := devilVerificationInformed(roomInt, checkidInt, identity)
		if !result {
			//告知出错
			http.Error(w, "Failed to inform", http.StatusInternalServerError)
			return
		}
	}
}

func Aiguard(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	skilltype := r.URL.Query().Get("type")
	skilltypeInt, err := strconv.Atoi(skilltype)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	lastchoose := r.URL.Query().Get("lastchoose")
	lastchooseInt, err := strconv.Atoi(lastchoose)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	namelist := NameList(7, roomInt)
	protectid := guardGuard(roomInt, namelist, skilltypeInt, lastchooseInt) //询问ai想要守卫的对象并返回守卫对象
	if protectid != 0 {
		fmt.Fprint(w, protectid)
		//返回要守护的玩家
	} else if protectid == -1 {
		fmt.Println("error to call guardGuard")
	} //调用的函数出错
	//返回ai守卫者想要守护的对象
}

// if checkid == -1 {
// 	//出现错误进行处理
// } else {
// 	roleint := 0
// 	handle, err := Connection()
// 	if err != nil {
// 		http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
// 		return
// 	}
// 	defer handle.Close()
// 	err = handle.QueryRow("SELECT Role FROM player WHERE No = ? AND RmNo = ?", checkid, roomInt).Scan(&roleint)
// 	if err != nil {
// 		http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
// 		return
// 	}
// 	if roleint > 0 {
// 		//数据库中查验成功，返回身份信息
// 		role := ""
// 		//根据role编号检查身份

// 		var wn0, fn0, setroles = 0, 0, ""
// 		err = handle.QueryRow("SELECT Role,Werewolf,Folk FROM game WHERE RmNo =?", roomno).Scan(&setroles, &wn0, &fn0)
// 		if err != nil {
// 			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
// 			return
// 		}
// 		var roles []string
// 		if setroles != "" {
// 			roles = strings.Split(setroles, ";")
// 		}

// 		for i := 0; i < wn0; i++ {
// 			roles = append(roles, "w")
// 		}
// 		for i := 0; i < fn0; i++ {
// 			roles = append(roles, "f")
// 		} //获取角色名单

// 		role = roles[roleint-1]
// 		switch {
// 		case role == "g-seer" || role == "g-witch" || role == "f":
// 			role = "好人"
// 		case role == "w":
// 			role = "坏人"
// 		}

// 		if result {
// 			fmt.Fprint(w, 1) //成功告知ai查验的对象的身份信息
// 			//成功告知ai预言家身份信息
// 		} else {
// 			fmt.Fprint(w, 0) //未成功告知ai预言家身份信息
// 		} //发生错误，进行处理

// 	}
// 	//查询数据库得到玩家的身份信息并返回给ai
//}

//询问ai语言家今天晚上要查询的玩家，并告知ai该玩家的身份

func Aivote(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	voteint := vote(roomInt) //获取投票号码
	if voteint == -1 {
		//出现错误进行处理
	} else {
		fmt.Fprint(w, voteint) //将整数写入数据的回复部分
	}

} //询问ai想要投票的对象

// func Aiinformed(w http.ResponseWriter, r *http.Request) {
// 	if r.Method != http.MethodGet {
// 		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
// 		return
// 	}
// 	roomno := r.URL.Query().Get("room")
// 	roomInt, err := strconv.Atoi(roomno)
// 	if err != nil {
// 		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
// 		return
// 	}
// } //其他玩家发言告知

func Aispeak(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	speakcontent := speak(roomInt) //获取ai发言内容
	if speakcontent == "" {
		//出现错误进行处理
	} else {
		fmt.Fprint(w, speakcontent) //将发言内容写入数据的回复部分
	}
} //ai玩家发言

func Nightinformation(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	death := r.URL.Query().Get("death")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	deathInformed(roomInt, death) //调用函数，告知ai昨晚的信息
}

func Voteout(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	voteout := r.URL.Query().Get("voteout")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	voteoutInt, err := strconv.Atoi(voteout)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	votedOutInformed(roomInt, voteoutInt) //调用函数，告知ai投票结果
}

func EndOfLifeSkill(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomnoInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}

	//type为2，在轮询中检测当前行动回合是否轮到局内ai玩家行动
	handle, err := core.Connection()
	if err != nil {
		http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer handle.Close()
	role := ""
	roleint := 0

	err = handle.QueryRow("SELECT Role,RoleInt FROM ai_info WHERE RmNo = ?", roomnoInt).Scan(&role, &roleint)
	if err != nil {
		http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
		return
	}
	var response struct {
		Role string `json:"role"` // 角色类型
		Kill int    `json:"kill"` // 杀死的目标编号
	} //回复
	if role == "w-king" {
		//询问ai是否使用狼王技能
		//此处标识返回的数据属于狼王
		namelist := NameList(5, roomnoInt)
		kill := wolveKingKill(roomnoInt, namelist)
		if kill != -1 {
			response = struct {
				Role string `json:"role"`
				Kill int    `json:"kill"`
			}{
				Role: "w-king",
				Kill: kill,
			}
		} else {
			fmt.Println("error to use wolveKingKill")
		}
	} else if role == "g-hunter" {
		namelist := NameList(7, roomnoInt)
		kill := hunterkill(roomnoInt, namelist)
		if kill != -1 {
			response = struct {
				Role string `json:"role"`
				Kill int    `json:"kill"`
			}{
				Role: "g-hunter",
				Kill: kill,
			}
		} else {
			fmt.Println("error to use hunterKill")
		}
	} else {
		//直接返回
		//此处标识返回的数据属于其他角色
		response = struct {
			Role string `json:"role"`
			Kill int    `json:"kill"`
		}{
			Role: "else",
			Kill: 0,
		}
	}
	// 设置响应头
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	// 将响应数据编码为 JSON 并写入 HTTP 响应
	err = json.NewEncoder(w).Encode(response)
	if err != nil {
		http.Error(w, "Failed to encode response: "+err.Error(), http.StatusInternalServerError)
		return
	}

} //ai发表临终遗言后调用，判断ai角色，如果是猎人或狼王，询问其使用技能的对象

func AiLastWord(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	speakcontent := lastWords(roomInt) //获取ai发言内容
	if speakcontent == "" {
		fmt.Println("error to get lastWords")
		//出现错误进行处理
	} else {
		fmt.Fprint(w, speakcontent) //将发言内容写入数据的回复部分
	}
} //获取ai遗言

// 询问ai狼王是否使用技能
func AiWolveKingKill(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	RoomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	namelist := NameList(5, RoomInt) //调用函数得出狼王可以击杀的对象列表
	id := wolveKingKill(RoomInt, namelist)
	//改写提供可以毒杀的对象列表

	if id == 0 {
		fmt.Fprint(w, 0) //将整数写入数据的回复部分
		//返回不使用技能
	} else if id > 0 {
		fmt.Fprint(w, id)
		//返回要击杀的玩家
	} else if id == -1 {
		fmt.Println("error to call wolveKingKill")
	} //调用的函数出错
}

func AiHunterKill(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	RoomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	namelist := NameList(4, RoomInt) //调用函数得出猎人可以击杀的对象列表
	id := hunterkill(RoomInt, namelist)
	//改写提供可以毒杀的对象列表

	if id == 0 {
		fmt.Fprint(w, 0) //将整数写入数据的回复部分
		//返回不使用技能
	} else if id > 0 {
		fmt.Fprint(w, id)
		//返回要击杀的玩家
	} else if id == -1 {
		fmt.Println("error to call wolveKingKill")
	} //调用的函数出错
}

//询问ai猎人是否使用技能

func AiKnightSkill(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	RoomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	namelist := NameList(6, RoomInt) //调用函数得出猎人可以击杀的对象列表
	id := knightDuelistkill(RoomInt, namelist)
	//改写提供可以毒杀的对象列表
	if id == 0 {
		fmt.Fprint(w, 0) //将整数写入数据的回复部分
		//返回不使用技能
	} else if id > 0 {
		fmt.Fprint(w, id)
		//返回要击杀的玩家
	} else if id == -1 {
		fmt.Println("error to call knightDuelistkill")
	} //调用的函数出错
}

//询问ai骑士是否使用技能

func AiselfDetonationInformed(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	id := r.URL.Query().Get("id")
	idInt, err := strconv.Atoi(id)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	selfDetonationInformed(roomInt, idInt) //调用函数，告知ai自爆信息
} //告知ai其他玩家的自爆信息

func Endgame(w http.ResponseWriter, r *http.Request) {

	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	roomno := r.URL.Query().Get("room")
	roomInt, err := strconv.Atoi(roomno)
	if err != nil {
		http.Error(w, "Failed to query:"+err.Error(), http.StatusInternalServerError)
		return
	}
	if roomInt > 0 && roomInt <= 100 {
		handle, err := core.Connection()
		if err != nil {
			http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		defer handle.Close()
		_, err = handle.Exec("DELETE FROM Ai_info WHERE RmNo = ?", roomInt) //删除ai_info表中记录的信息
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
		_, err = handle.Exec("DELETE FROM message WHERE room_id = ?", roomInt) //删除message表中记录的与ai的对话信息
		if err != nil {
			http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
			return
		}
	}
} //游戏结束，删除ai对话数据库内当前房间的所有信息

func Airoleinformed(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Airoleinformed")
	room := r.URL.Query().Get("room")
	roomint, err := strconv.Atoi(room)
	if err != nil {
		http.Error(w, "Invalid room", http.StatusBadRequest)
		return
	}
	handle, err := core.Connection()
	if err != nil {
		http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer handle.Close()
	addRole := ""
	wn0 := 0
	fn0 := 0
	airole := 0
	err = handle.QueryRow("SELECT Role,Werewolf,Folk FROM game WHERE RmNo =?", room).Scan(&addRole, &wn0, &fn0)
	var roles []string
	if addRole != "" {
		roles = strings.Split(addRole, ";")
	}
	//此处加入了所有特殊角色
	for i := 0; i < wn0; i++ {
		roles = append(roles, "w")
	}
	for i := 0; i < fn0; i++ {
		roles = append(roles, "f")
	} //加入普通狼和平民
	handle.QueryRow("SELECT RoleInt FROM ai_info WHERE RmNo = ?", roomint).Scan(&airole)
	if err != nil {
		http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError)
		return
	}
	
	role := ""
	switch roles[airole-1] {
	case "w":
		role = "狼人"
	case "f":
		role = "平民"
	case "g-seer":
		role = "预言家"
	case "g-witch":
		role = "女巫"
	case "g-guard":
		role = "守卫"
	case "g-hunter":
		role = "猎人"
	case "w-devil":
		role = "恶魔"
	case "w-king":
		role = "狼王"
	case "g-knight":
		role = "骑士"
	case "w-knight":
		role = "恶灵骑士"
	}
	handle.Exec("UPDATE ai_info SET Role = ? WHERE RmNo = ?", roles[airole-1], roomint) //修正ai_info表中ai的角色
	kimirespone := gameStart(roomint, role, 1)
	//告知ai其角色
	if !kimirespone {
		http.Error(w, "kimi role informed failed", http.StatusInternalServerError) //告知ai角色失败
	}
}
